// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.jasmin.chips;

/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class Memory2 implements Chip {
  public final IntBus ADDRESS = new IntBus();
  public final ByteBus DATA = new ByteBus();
  public final Pin WR = new Pin();
  public final Pin REQ = new Pin();
  
  private final int mask;
  final byte[] mem;
  
  public Memory2(int addressBits) {
    this.mask = (1 << addressBits) - 1;
    this.mem = new byte[1 << addressBits];
  }
  
  public void update() {
    if (REQ.value) {
      if (WR.value) {
        mem[ADDRESS.value & mask] = DATA.value;
        DATA.isActive = false;
      } else {
        DATA.value = mem[ADDRESS.value & mask];
        DATA.isActive = true;
      }
    } else {
      DATA.isActive = false;
    }
  }
}
